const router = require('koa-router')()
const mysql = require('../../db')
const multer = require('koa-multer');
const path = require('path');
router.prefix('/product')

let storage = multer.diskStorage({
  destination: path.resolve('public/images/car/product'),
  filename: (ctx, file, cb)=>{
    let suffix = file.originalname.split('.')[1];
      cb(null, Date.now()+"."+suffix);
  }
});
let fileFilter = (ctx, file ,cb)=>{
let suffix = file.originalname.split('.')[1];
  if (!suffix in ['jpg','png','jpeg','gif']){
      cb(null, false); 
  }else {
      cb(null, true); 
  }
}
let upload = multer({ storage: storage, fileFilter: fileFilter });

router.post('/', upload.single('pic'), async (ctx, next) => {
  try {
    let { ca_p_id} = ctx.req.body
    ca_p_id = parseInt(ca_p_id)
    let file = ctx.req.file;
    ca_img = 'product/' + file.filename;
    let sql = `update product set p_picture=? where p_id=?`;
    let result = await mysql(sql, [ca_img, ca_p_id]);
    sql = `insert into imgcar(img_url,img_p_id) values(?,?)`
    let result1 = await mysql(sql, [ca_img, ca_p_id]);
    if (result.affectedRows > 0 &&result1.affectedRows>0) {
      ctx.body = `<h3>上传成功^_^</h3>
        <div>该页面将在<span id="time"></span>秒后退出！</div>
        <script>
          let time = 5;
          setInterval(()=>{
            document.getElementById("time").innerText = time;
            if(time<0){
              window.location.href = "http://localhost:3051/"
            }
            time--;
          },1000)
        </script>`;
    }
  } catch (error) {
    next(error)
  }
})

module.exports=router